package com.sreManager.service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sreManager.domain.LoginUsers;
import com.sreManager.domain.Logs;
import com.sreManager.mapper.LogsMapper;
import com.sreManager.web.util.LoginManager;

@Service
public class LogsService {

	@Autowired LogsMapper logsMapper;

	String userIp;

	public HashMap<String, String> menuUsed ;
	public HashMap<String, String> logType ;

	public LogsService() {
		setMenuUsed();
		setLogType();
	}

	public String getUserIp() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostAddress();
	}

	public void insertLog(HttpServletRequest request, String type, String menu) throws UnknownHostException {
		LoginUsers loginUser = LoginManager.getInstance().getSession(request);

		Logs logs = new Logs();
		logs.setUserId(loginUser.getId());
		logs.setUserName(loginUser.getName());
		logs.setUserIp(this.getUserIp());
		logs.setLogsType(type);
		logs.setLogsTypeTxt(logType.get(type));
		logs.setMenuUsed(menu);
		logs.setMenuUsedTxt(menuUsed.get(menu));
		logsMapper.insertLog(logs);
	}

	public HashMap<String, String> setMenuUsed() {
		menuUsed = new HashMap<String, String>();
		menuUsed.put("search", "검색");
		menuUsed.put("company", "업체등록");
		menuUsed.put("user", "사용자권한");
		menuUsed.put("log", "로그관리");
		menuUsed.put("upload1", "업로드관리 - 사업자정보");
		menuUsed.put("upload2", "업로드관리 - 측정정보");
		return menuUsed;
	}

	public HashMap<String, String> setLogType() {
		logType = new HashMap<String, String>();
		logType.put("login", "로그인");
		logType.put("reg", "등록");
		logType.put("mod", "수정");
		logType.put("del", "삭제");
		logType.put("view", "상세보기");
		logType.put("list", "목록");
		logType.put("search", "검색");
		logType.put("excel", "엑셀다운");
		logType.put("upload", "엑셀업로드");
		return logType;
	}

	public void insertLog(HttpServletRequest request, String type, String menu, String msg) throws UnknownHostException {
		LoginUsers loginUser = LoginManager.getInstance().getSession(request);

		Logs logs = new Logs();
		logs.setUserId(loginUser.getId());
		logs.setUserName(loginUser.getName());
		logs.setUserIp(this.getUserIp());
		logs.setLogsType(type);
		logs.setLogsTypeTxt(logType.get(type));
		logs.setMenuUsed(menu);
		logs.setMenuUsedTxt(menuUsed.get(menu));
		if(msg==null) msg = "";
		logs.setMsg(msg);
		logsMapper.insertLog(logs);
	}
}
